<?php
namespace App\Http\Controllers\Merchant;
use App\Http\Controllers\BaseController;
use App\Models\Merchant;
use Illuminate\Http\Request;

class AdminController extends BaseController
{

    public function store(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'phone'  => 'required',
            'category' => 'required',
        ]);

        $id = $this->getUserId();
        unset($input['balance_yuan'], $input['type_show']);
        $exist_id = Merchant::where('phone', \request('phone'))
            ->where('category', \request('category'))
            ->whereIn('audit_status', [0, 1])->value('id');
        if ($id) {
            if ($exist_id && ($id != $exist_id)) {
                return $this->failed("手机号已经存在");
            }
            Merchant::where('id', $id)->update($input);
        } else {
            if ($exist_id)
                return $this->failed("手机号已经存在");

            $input['raw_password'] = create_password(6);
            $input['password'] = bcrypt($input['raw_password']);
            $admin = Merchant::create($input);
            $id = $admin->id;
        }
        return $this->success(['id' => $id]);
    }


    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:merchants'
        ]);
        $id = \request("id");
        $info = Merchant::find($id);
        return $this->success($info);
    }

    public function updatePwd(Request $request) {
        $input = $request->input();
        $this->validate($request, [
            'password'  => 'required|min:6|max:14',
            'password_confirmation' => 'required|same:password'
        ]);
        $user = $this->getUser();
        $user->raw_password = $input['password'];
        $user->password = bcrypt($input['password']);
        if ($user->save()){
            auth('merchant')->refresh();
            $token = auth('merchant')->login($user);
            return $this->respondWithToken($token);
        }
        return $this->failed('创建失败');
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:merchants'
        ]);
        $id = $request->input('id');
        Merchant::where('id', $id)->delete();
        return $this->success([]);
    }

    public function logout(Request $request) {
        auth()->logout();
        return $this->success([]);
    }

    public function resetPassword(Request $request) {
        $this->validate($request, [
            'id'   => 'required',
        ]);
        $id = \request('id');
        $admin = Merchant::find($id);
        if (!$admin)
            return $this->failed('ID无效');
        $admin->password = bcrypt('abc123456');
        $admin->save();
        return $this->success([], '重置成功');
    }

}

